<%@ Page Language="C#" MasterPageFile="~/master/admin.master" AutoEventWireup="true"
    CodeFile="product-category.aspx.cs" Inherits="admin_product_category" Title="Untitled Page" %>

<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<%@ Register Namespace="ECommerce.Library.Web" TagPrefix="ucc" %>
<asp:Content ID="cntMiddleContent" ContentPlaceHolderID="cphMiddleContent" runat="Server">
    <script type="text/javascript">

        var resolveCategoryImageUrl = function (value, p, record, rowIndex) {

            //alert(value);

            var imageUrl;
            if (value != "")
                imageUrl = record.data.CategoryImageUrl.replace("~/", "<%= SiteGlobals.BaseUrl %>");
            else
                imageUrl = "<%= AutoGear.BLL.SiteSettings.NoImageUrl %>";

            /*var jsonData = JSON.stringify({ url: value });

            $.ajax({
            url: "<%= SiteGlobals.BaseUrl %>_services/Utilities.asmx/ResolveUrl",
            async: false,
            data: jsonData,
            type: "post",
            processData: false,
            contentType: "application/json",
            dataType: "text",
            success:
            function (result) {
            imageUrl = JSON.parse(result).d;
            }
            });*/

            return '<img src="' + imageUrl + '" class="listingImage" />';
        };

        var CategoryName_Render = function (value, p, record, rowIndex) {
            var rootCategoryId = "<%= AutoGear.BLL.SiteUtility.SuperRootCategoryId %>";
            var categoryUrl = "<%= SiteGlobals.BaseUrl %>" + "admin/product-category-edit.aspx?cid=" + record.data.CategoryId;

            if (record.data.ParentCategoryId == rootCategoryId)
                return '<a href="' + categoryUrl + '" class="leftlink">' + value + '</a>';
            else
                return '<a href="' + categoryUrl + '" class="leftlink2">' + value + '</a>';
        };

        var IsActive_Renderer = function (value) {
            if (value == true)
                return "Yes";
            else
                return "No";
        }

        var CommandHandler = function (command, rowIndex, grid) {
            //showObj(grid);
            grid.getRowEditor().stopEditing();
            grid.getView().refresh();
            grid.getSelectionModel().selectRow(rowIndex);
            grid.getRowEditor().startEditing(rowIndex);
        }

        var afterEdit = function (e) {
            /*
            Properties of 'e' include:
            e.grid - This grid
            e.record - The record being edited
            e.field - The field name being edited
            e.value - The value being set
            e.originalValue - The original value for the field, before the edit.
            e.row - The grid row index
            e.column - The grid column index
            */
            e.grid.stopEditing();
            //alert(e.record.data.CategoryName);

            // Call DirectMethod
            Polana.WebService.UpdateCategory(e.record.data.CategoryId, e.record.data.CategoryName, e.record.data.DisplayOrder, e.record.data.IsActive);
        };

        var categoryGrid;

        var deleteCategories = function () {
            if (categoryGrid != null) {
                categoryGrid.getRowEditor().stopEditing();

                var s = categoryGrid.getSelectionModel().getSelections();
                if (s.length > 0) {

                    if (confirm("Are you sure you want to delete these categories?")) {

                        var ids = "";

                        for (var i = 0, r; r = s[i]; i++) {
                            ids = ids + " " + r.data.CategoryId;
                        }

                        // Call DirectMethod
                        Polana.WebService.DeleteCategories(ids);
                    }
                }
            }
        }

        var searchCategory = function (grid) {
            Polana.WebService.SearchCategory();

            //var options = grid.store.lastOptions;
            //grid.getStore().reload(options);
        }

        var addCategory = function () {
            window.location = "<%= SiteGlobals.BaseUrl %>" + "admin/product-category-add.aspx";
        }

        var onDocumentReady = function (grid) {
            categoryGrid = grid;
        }

    </script>
    <ext:ResourceManager ID="ScriptManager1" runat="server" Theme="Gray">
        <Listeners>
            <DocumentReady Fn="onDocumentReady(#{GridPanel1})" />
        </Listeners>
    </ext:ResourceManager>
    <ext:Store ID="Store1" runat="server" RemoteSort="true" OnRefreshData="Store1_RefreshData">
        <AutoLoadParams>
            <ext:Parameter Name="sort" Value="CategoryId" Mode="Value" />
            <ext:Parameter Name="start" Value="0" Mode="Raw" />
            <ext:Parameter Name="limit" Value="50" Mode="Raw" />
        </AutoLoadParams>
        <Proxy>
            <ext:PageProxy />
        </Proxy>
        <Reader>
            <ext:JsonReader IDProperty="CategoryId">
                <Fields>
                    <ext:RecordField Name="CategoryId" />
                    <ext:RecordField Name="ParentCategoryId" />
                    <ext:RecordField Name="CategoryName" Type="String" />
                    <ext:RecordField Name="CategoryUrl" Type="String" />
                    <ext:RecordField Name="CategoryImageUrl" Type="String" />
                    <ext:RecordField Name="DisplayOrder" Type="String" />
                    <ext:RecordField Name="IsActive" Type="Boolean" />
                    <ext:RecordField Name="CreateDate" Type="Date" />
                </Fields>
            </ext:JsonReader>
        </Reader>
    </ext:Store>
    <div class="admin-function-top inline">
        <%--<asp:TextBox ID="tbxSearchByName" runat="server" CssClass="text" Text="Search by Category Name"
            onclick="clearText(this, 'Search by Category Name', '#000000')" onblur="resetText(this, 'Search by Category Name', '#000000')"></asp:TextBox>
        <asp:DropDownList ID="ddlParent" runat="server" AppendDataBoundItems="true">
            <asp:ListItem Text="Select Parent Category" Value=""></asp:ListItem>
        </asp:DropDownList>
        <asp:Button ID="imgSearchButton" runat="server" CssClass="btn-regular" Text="Search"
            OnClick="imgSearchButton_Click" />
        <a href="<%= AutoGear.BLL.CustomSiteMap.CategoryAdd %>">
            <asp:Button runat="server" ID="imgAddButton" CssClass="btn-regular" Text="Add Category" />
        </a>--%>
        <ucc:ResponseMessage ID="uccResponseMessage" runat="server"></ucc:ResponseMessage>
        <ext:GridPanel ID="GridPanel1" runat="server" EnableViewState="true" AutoHeight="true"
            StoreID="Store1">
            <ColumnModel>
                <Columns>
                    <ext:Column Header="Category Logo" DataIndex="CategoryImageUrl" Sortable="false"
                        Resizable="false" Width="150">
                        <Renderer Fn="resolveCategoryImageUrl" />
                    </ext:Column>
                    <ext:Column Header="Category Name" Width="100" DataIndex="CategoryName">
                        <Renderer Fn="CategoryName_Render" />
                        <Editor>
                            <ext:TextField ID="txtCategoryName" runat="server" />
                        </Editor>
                    </ext:Column>
                    <ext:Column Header="Display Order" Width="40" DataIndex="DisplayOrder">
                        <Editor>
                            <ext:TextField ID="txtDisplayOrder" runat="server" />
                        </Editor>
                    </ext:Column>
                    <ext:Column Header="Active" DataIndex="IsActive" Width="40">
                        <Renderer Fn="IsActive_Renderer" />
                        <Editor>
                            <ext:Checkbox ID="chkIsActive" runat="server" />
                        </Editor>
                    </ext:Column>
                    <ext:CommandColumn Width="30">
                        <Commands>
                            <ext:GridCommand Icon="NoteEdit" CommandName="Edit" Text="Edit" />
                        </Commands>
                    </ext:CommandColumn>
                </Columns>
            </ColumnModel>
            <TopBar>
                <%--<ext:PagingToolbar ID="PagingToolbar2" runat="server" PageSize="10" DisplayInfo="true"
                            DisplayMsg="Displaying categories {0} - {1} of {2}" EmptyMsg="No categories to display"
                            AutoWidth="true" />--%>
                <ext:Toolbar ID="ActionToolBar" runat="server">
                    <Items>
                        <ext:TextField ID="txtToolbarSearch" runat="server" EmptyText="Search by Category Name"
                            FieldClass="text" EnableKeyEvents="true">
                            <Listeners>
                                <KeyPress Handler="if(e.getKey() == Ext.EventObject.ENTER){e.preventDefault(); searchCategory(#{GridPanel1})}" />
                            </Listeners>
                        </ext:TextField>
                        <ext:ComboBox ID="ddlToolbarCategories" runat="server" Mode="Remote" TriggerIcon="SimpleArrowDown"
                            EmptyText="Select Parent Category" EnableKeyEvents="true">
                              <Listeners>
                                <KeyPress Handler="if(e.getKey() == Ext.EventObject.ENTER){e.preventDefault(); searchCategory(#{GridPanel1})}" />
                            </Listeners>
                        </ext:ComboBox>
                        <ext:Button ID="btnToolbarSearch" runat="server" Text="Search" Icon="Magnifier">
                            <Listeners>
                                <Click Handler="searchCategory(#{GridPanel1});" />
                            </Listeners>
                        </ext:Button>
                        <ext:Button ID="btnToolbarAddCategory" runat="server" Text="Add Category" Icon="Add">
                            <Listeners>
                                <Click Handler="addCategory();" />
                            </Listeners>
                        </ext:Button>
                        <ext:ToolbarFill ID="ToolbarFill1" runat="server" />
                        <ext:Button ID="btnToolbarDelete" runat="server" Text="Delete selected" Icon="Delete" >
                            <Listeners>
                                <Click Handler="deleteCategories();" />
                            </Listeners>
                        </ext:Button>
                    </Items>
                </ext:Toolbar>
            </TopBar>
            <BottomBar>
                <ext:PagingToolbar ID="PagingToolbar1" runat="server" PageSize="50" DisplayInfo="true"
                    DisplayMsg="Displaying categories {0} - {1} of {2}" EmptyMsg="No categories to display"
                    AutoWidth="true" />
            </BottomBar>
            <LoadMask ShowMask="true" />
            <SelectionModel>
                <ext:CheckboxSelectionModel ID="CheckboxSelectionModel1" runat="server" ColumnPosition="5"
                    AllowDeselect="true" CheckOnly="true" />
            </SelectionModel>
            <Plugins>
                <ext:RowEditor ID="rowedi" runat="server" SaveText="Update" ClicksToEdit="2" ErrorSummary="false"
                    ShowTooltip="={Ext.emptyFn}">
                    <Listeners>
                        <AfterEdit Fn="afterEdit" />
                    </Listeners>
                </ext:RowEditor>
            </Plugins>
            <Listeners>
                <Command Handler="CommandHandler(command, rowIndex, this)" />
            </Listeners>
            <View>
                <ext:GridView ID="GridView1" runat="server" ForceFit="true" />
            </View>
        </ext:GridPanel>
    </div>
    <script type="text/javascript">
        Ext.override(Ext.grid.GridView, {
            getEditorParent: function () {
                return document.body;
            }
        });
    </script>
</asp:Content>
